<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 救火队队长
// +----------------------------------------------------------------------

namespace app\common\model;

use app\common\model\UserLog;
use think\facade\Db;
use think\model\concern\SoftDelete;
use app\api\controller\EmailSend;
use app\api\controller\PublicApi;

class User extends Common
{
    use SoftDelete;
    protected $deleteTime = 'isdel';

    protected $autoWriteTimestamp = true;
    protected $updateTime = 'utime';

    const STATUS_NORMAL = 1;        //用户状态 正常
    const STATUS_DISABLE = 2;       //用户状态 停用

    /**
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdmin($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];

        $order_sort = "ctime desc";

        if(isset($post['username']) && !empty($post['username'])){
            $where[] = ['username', 'like', '%' . trim($post['username']) . '%'];
        }
        if(isset($post['business_token']) && !empty($post['business_token'])){
            $where[] = ['business_token', 'like', '%' . trim($post['business_token']) . '%'];
        }
        if(isset($post['user_memo']) && !empty($post['user_memo'])){
            $where[] = ['user_num', 'like', '%' . trim($post['user_memo']) . '%'];
        }
        if(isset($post['grade']) && strlen($post['grade']) > 0){
            $where[] = ['grade', '=', $post['grade']];
        }
        if(isset($post['grade_new']) && strlen($post['grade_new']) > 0){
            $where[] = ['grade_new', '=', $post['grade_new']];
        }
        if(isset($post['user_fz']) && strlen($post['user_fz']) > 0){
            $where[] = ['balance', '<', 0];
            $order_sort = "balance asc";
        }
        if(isset($post['check_ip']) && strlen($post['check_ip']) > 0){
            $where[] = ['is_check', '=', $post['check_ip']];
        }
        if(isset($post['tran_code']) && strlen($post['tran_code']) > 0){
            $where[] = ['is_code', '=', $post['tran_code']];
        }
        if(isset($post['status_num']) && strlen($post['status_num']) > 0){
            $where[] = ['status', '=', $post['status_num']];
        }

//        $where[] = ['fc.type', '=', 0];
//        $where[] = ['fc.check_status', '=', 1];
//        if(isset($post['is_fund']) && strlen($post['is_fund']) > 0){
//
//        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00");
            $end_time   = strtotime($time_list[1] . " 23:59:59");
            $where[] = ['ctime', 'between', "{$start_time},{$end_time}"];
        }

        $fund_total_list = Db::name('fund_check')
            ->field("sum(amount) as fund_amount , user_id")
            ->where('check_status=1 and type=0')
            ->group('user_id')->select()->toArray();
        $fund_user_list = [];
        $user_id_array  = '';
        foreach ($fund_total_list as $k=>$v){
            $fund_user_list[$v['user_id']] = $v['fund_amount'];
            $user_id_array .= $v['user_id'] . ',';
        }

        $fund_total_list_debit = Db::name('fund_check')
            ->field("sum(amount) as fund_amount , user_id")
            ->where('check_status=1 and type=1')
            ->group('user_id')->select()->toArray();
        $fund_user_list_debit = [];
        foreach ($fund_total_list_debit as $k=>$v){
            $fund_user_list_debit[$v['user_id']] = $v['fund_amount'];
        }


        $user_id_array = trim($user_id_array , ',');
        if(isset($post['is_fund']) && strlen($post['is_fund']) > 0){
            if($post['is_fund'] == 1){
                $where[] = ['id', 'in', "({$user_id_array})"];
            }else{
                $where[] = ['id', 'not in', "({$user_id_array})"];
                $where[] = ['id', '<>', 1];
            }
        }

        $card_amount_list =[];
        $cards_list = Db::name('cards')
            ->field("sum(balance) as card_balance , user_id")
            ->group('user_id')->select()->toArray();
        foreach ($cards_list as $k_card=>$v_card){
            $card_amount_list[$v_card['user_id']] = $v_card['card_balance'];
        }

        //usdt汇率
        $usdt_rate_array = [];
        $usdt_rate_list  = Db::name('user_oy_set')->field('user_id,rate')->select()->toArray();
        foreach ($usdt_rate_list as $v_usdt){
            $usdt_rate_array[$v_usdt['user_id']] = $v_usdt['rate'];
        }
        $list = Db::name('user')
            ->where($where)
            ->order($order_sort)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        foreach ($list['data'] as $k_re => &$v_re){
            $credit = $fund_user_list[$v_re['id']] ?? 0.00;
            $debit  = $fund_user_list_debit[$v_re['id']] ?? 0.00;
            $v_re['fund_amount'] =  $credit - $debit;
            $v_re['card_amount'] = $card_amount_list[$v_re['id']] ?? 0.00;
            $v_re['usdt_rate'] = $usdt_rate_array[$v_re['id']] ?? '--';
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function tableDataAdminRate($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];

        $rate  = Db::name('user')->where(['id'=>1])->value('usa_rate');
        $where[] = ['usa_rate', '<>', $rate];
        $list = Db::name('user')
            ->where($where)
            ->order('id desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function tableDataAdminBold($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['username']) && !empty($post['username'])){
            $where[] = ['username', 'like', '%' . trim($post['username']) . '%'];
        }
        if(isset($post['business_token']) && !empty($post['business_token'])){
            $where[] = ['business_token', 'like', '%' . trim($post['business_token']) . '%'];
        }
        if(isset($post['user_memo']) && !empty($post['user_memo'])){
            $where[] = ['user_num', 'like', '%' . trim($post['user_memo']) . '%'];
        }
        if(isset($post['grade']) && strlen($post['grade']) > 0){
            $where[] = ['grade', '=', $post['grade']];
        }
        if(isset($post['grade_new']) && strlen($post['grade_new']) > 0){
            $where[] = ['grade_new', '=', $post['grade_new']];
        }
        if(isset($post['user_fz']) && strlen($post['user_fz']) > 0){
            $where[] = ['balance', '<', 0];
        }
        if(isset($post['check_ip']) && strlen($post['check_ip']) > 0){
            $where[] = ['is_check', '=', $post['check_ip']];
        }
        if(isset($post['tran_code']) && strlen($post['tran_code']) > 0){
            $where[] = ['is_code', '=', $post['tran_code']];
        }

        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00");
            $end_time   = strtotime($time_list[1] . " 23:59:59");
            $where[] = ['ctime', 'between', "{$start_time},{$end_time}"];
        }

        $fund_total_list = Db::name('fund_check')
            ->field("sum(amount) as fund_amount , user_id")
            ->where('check_status=1 and type=0')
            ->group('user_id')->select()->toArray();
        $fund_user_list = [];
        $user_id_array  = '';
        foreach ($fund_total_list as $k=>$v){
            $fund_user_list[$v['user_id']] = $v['fund_amount'];
            $user_id_array .= $v['user_id'] . ',';
        }

        $fund_total_list_debit = Db::name('fund_check')
            ->field("sum(amount) as fund_amount , user_id")
            ->where('check_status=1 and type=1')
            ->group('user_id')->select()->toArray();
        $fund_user_list_debit = [];
        foreach ($fund_total_list_debit as $k=>$v){
            $fund_user_list_debit[$v['user_id']] = $v['fund_amount'];
        }


        $user_id_array = trim($user_id_array , ',');
        if(isset($post['is_fund']) && strlen($post['is_fund']) > 0){
            $where[] = ['id', 'in', "({$user_id_array})"];
        }

        $card_amount_list =[];
        $cards_list = Db::name('cards')
            ->field("sum(balance) as card_balance , user_id")
            ->group('user_id')->select()->toArray();
        foreach ($cards_list as $k_card=>$v_card){
            $card_amount_list[$v_card['user_id']] = $v_card['card_balance'];
        }

        $list_set = Db::name('user_set')->select()->toArray();
        $set_id_array = [];
        foreach ($list_set as $k_set=>$v_set){
            $card_set = json_decode($v_set['card_set'] , true);

            foreach ($card_set as $kk_set=>$vv_set){
                if($vv_set['rate_fund'] -0 == 0){
                    if(!in_array($v_set['user_id'] , $set_id_array)){
                        $set_id_array[] = $v_set['user_id'];
                    }
                }
            }
        }
        $set_id_value= '';
        foreach ($set_id_array as $kk_setT=>$vv_setT){
            $set_id_value .= $vv_setT . ',';
        }
        $set_id_value = trim($set_id_value , ',');
        $where[] = ['id', 'in', $set_id_value];

        $list = Db::name('user')
            ->where($where)
            ->order('ctime desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        foreach ($list['data'] as $k_re => &$v_re){
            $credit = $fund_user_list[$v_re['id']] ?? 0.00;
            $debit  = $fund_user_list_debit[$v_re['id']] ?? 0.00;
            $v_re['fund_amount'] =  $credit - $debit;
            $v_re['card_amount'] = $card_amount_list[$v_re['id']] ?? 0.00;
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    /**
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdminTwo($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $order = "user_id desc";
        if(isset($post['username']) && !empty($post['username'])){
            $where[] = ['username', 'like', '%' . trim($post['username']) . '%'];
        }
        if(isset($post['desc_list']) && !empty($post['desc_list'])){
            $order = $post['desc_list'] . " desc";
        }

        $list = Db::name('user_data')
            ->where($where)
            ->order($order)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    /**
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdminThree($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $order = "diff_amount asc";
        $where =[];
        if(isset($post['username']) && !empty($post['username'])){
            $where[] = ['username', 'like', '%' . trim($post['username']) . '%'];
        }

        $list = Db::name('user_data_diff')
            ->where($where)
            ->order($order)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        if($list){
            foreach ($list['data'] as $k=>&$v){
                $fund_total = $v['fund_total'];
                $total_amount = $v['total_amount'];
                $v['set_amount'] = 0;
                if($total_amount - $fund_total != 0){
                    $v['set_amount'] = getSprintf(round($fund_total - $total_amount , 2));
                }
            }
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    /**
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataHistory($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
            $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
            $where[] = ['ctime', 'between', "{$start_time},{$end_time}"];
        }
        $list = Db::name('user_data_history')
            ->where($where)
            ->order('ctime desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    /**
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdminOther($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
            $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
            $where[] = ['ctime', 'between', "{$start_time},{$end_time}"];
        }
        $list = Db::name('user_data_other')
            ->where($where)
            ->order('ctime desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function changeAmount($data)
    {
        $user_id    = $data['user_id'];
        $manage_id  = $data['manage_id'];
        $money      = $data['money'];
        $result     = Db::name('user')->where(['id'=>$user_id])->update(['create_amount'=>$money]);
        ManageLog::saveManageLog([
            'manage_id' => $manage_id,
            'desc'      => 'update create card amount',
            'content'   => ['user_id' => $user_id, 'create_amount' => $money]
        ]);
        return $result;
    }

    public function changeOpen($data)
    {
        $user_id    = $data['user_id'];
        $manage_id  = $data['manage_id'];
        $money      = $data['open_money'];
        $result     = Db::name('user')->where(['id'=>$user_id])->update(['open_amount'=>$money]);
        ManageLog::saveManageLog([
            'manage_id' => $manage_id,
            'desc'      => 'update open card amount',
            'content'   => ['user_id' => $user_id, 'open_money' => $money]
        ]);
        return $result;
    }

    public function editMax($data)
    {
        $user_id    = $data['user_id'];
        $manage_id  = $data['manage_id'];
        $card_max   = $data['card_max'];
        $old_num    = Db::name('user')->where(['id'=>$user_id])->value('card_max');
        $result     = Db::name('user')->where(['id'=>$user_id])->update(['card_max'=>$card_max]);
        Db::name('manage_card')->save([
            'user_id'   => $user_id,
            'manage_id' => $manage_id,
            'old_num'   => $old_num,
            'new_num'   => $card_max,
            'ctime'     => getUtcTime()
        ]);
        ManageLog::saveManageLog([
            'manage_id' => $manage_id,
            'desc'      => 'update Card Max',
            'content'   => ['user_id' => $user_id, 'card_max' => $card_max]
        ]);
        return $result;
    }

    public function changePwd($data)
    {
        $user_id    = $data['user_id'];
        $manage_id  = $data['manage_id'];
        $pwd        = $data['pwd'];

        $result     = [
            'blog'  => true,
            'msg'   => ''
        ];
        $user_list  = Db::name('user')->where(['id'=>$user_id])->find();
        $user_ctime = $user_list['ctime'];
        $username   = $user_list['username'];
        $password   = $user_list['password'];

        $new_pwd    = md5(md5($pwd) . $user_ctime);

        if($password == $new_pwd){
            $result     = [
                'blog'  => false,
                'msg'   => 'The new password is the same as the old one.'
            ];
            return $result;
        }
        $update_result  = Db::name('user')->where(['id'=>$user_id])->update(['password'=>$new_pwd]);
        if($update_result){
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => 'Update User Password',
                'content'   => ['username' => $username, 'new_pwd' => $pwd]
            ]);
        }else{
            $result     = [
                'blog'  => false,
                'msg'   => 'Confirm the failed.'
            ];
        }
        return $result;
    }

    public function changeBalance($data)
    {
        $user_id    = $data['user_id'];
        $remark     = $data['remark'];
        $up_status  = $data['up_status'];
        $manage_id  = $data['manage_id'];
        $money      = $data['money'];
        $money_abs  = abs($money);

        $user_name       = $data['username'];
        $current_user_balance = $data['balance'];

        $manage_balance = Db::name('manage')->where(['id'=> $manage_id])->value('balance');
        if($money >0){
            $result_balance = $current_user_balance + $money_abs;
            $result_manage_balance = $manage_balance - $money_abs;
        }else{
            $result_balance = $current_user_balance - $money_abs;
            $result_manage_balance = $manage_balance + $money_abs;
        }
        $blog = true;
        Db::startTrans();
        try{
            $ctime = getUtcTime();
            $desc  = 'Manager ' . (($money >0)? 'Deposit':'Deduct');
            Db::name('user')
                ->where(['id'=>$user_id,'balance'=>$current_user_balance])
                ->update(['balance'=>$result_balance]);
            //记录钱包记录
            Db::name('user_cash_log')->save([
                'user_id'       => $user_id,
                'type'          => ($money >0) ? 0 : 1, //类型 0,Credit|1,Debit
                'action_type'   => ($money >0) ? 1 : 2, //操作类型 1,充值|2,提现
                'amount'        => $money_abs,
                'balance'       => $result_balance,
                'desc'          => !empty($remark)?$remark:$desc,
                'ctime'         => $ctime
            ]);
            if($up_status == 1){
                //记录充值记录
                Db::name('fund_check')->save([
                    'user_id'       => $user_id,
                    'check_num'     => 'manage',
                    'type'          => ($money >0) ? 0 : 1, //类型 0,Credit|1,Debit
                    'check_status'  => 1, //审核状态0,待审核|1,已通过|2,未通过
                    'pay_type'      => 0,
                    'amount'        => $money_abs,
                    'balance'       => $result_balance,
                    'desc'          => !empty($remark)?$remark:$desc,
                    'ctime'         => $ctime,
                    'utime'         => $ctime
                ]);
            }
            //记录管理员钱包日志
            $manage_desc  = 'Manager ' . (($money >0)? 'Deduct':'Deposit');
            Db::name('manage_fund_log')->save([
                'user_id'       => $user_id,
                'type'          => ($money >0) ? 1 : 0, //类型 0,Credit|1,Debit
                'amount'        => $money_abs,
                'manage_id'     => $manage_id,
                'manage_id_action'=>$manage_id, //管理员操作人
                'balance'       => $result_manage_balance,
                'remark'        => !empty($remark)?$remark:$manage_desc,
                'ctime'         => $ctime
            ]);
            Db::name('manage')->where(['id'=>$manage_id])->update(['balance'=>$result_manage_balance]);
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => $desc,
                'content'   => ['username' => $user_name,
                    'amount' => $money ,
                    'balance' => $result_balance,
                    'up_status' => ($up_status==1) ? 'Save':'unSave'
                ]
            ]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }
        return $blog;

    }

    public function changeStatus($data)
    {
        $user_id        = $data['user_id'];
        $manage_id      = $data['manage_id'];

        $user_list      = Db::name("user")->find($user_id);
        $user_name      = $user_list['username'];
        $current_status = $user_list['status'];
        if($current_status == 1){
            $new_status = 2;
        }else{
            $new_status = 1;
        }
        $blog = true;
        Db::startTrans();
        try{
            $ctime = getUtcTime();
            Db::name('user')->where(['id'=>$user_id])
                ->update(['status' => $new_status ]);
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => "更新用户状态",
                'content'   => [
                    'username'      => $user_name,
                    'old_status'    => ($current_status == 1)?'open':'ice' ,
                    'new_status'    => ($new_status == 1)?'open':'ice'
                ],
                'ctime'     => $ctime
            ]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }
        return $blog;
    }

    /**
     * 确定更新 (登录验证IP地址) 状态
     * @param $data
     * @return bool
     */
    public function isCheck($data)
    {
        $user_id        = $data['user_id'];
        $manage_id      = $data['manage_id'];

        $user_list      = Db::name("user")->find($user_id);
        $user_name      = $user_list['username'];
        $current_check  = $user_list['is_check'];
        if($current_check == 1){
            $new_check = 0;
        }else{
            $new_check = 1;
        }
        $blog = true;
        Db::startTrans();
        try{
            $ctime = getUtcTime();
            Db::name('user')->where(['id'=>$user_id])
                ->update(['is_check' => $new_check]);
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => "更新用户验证状态",
                'content'   => [
                    'username'      => $user_name,
                    'old_check'    => ($new_check == 1)?'不验证':'验证' ,
                    'new_check'    => ($new_check == 1)?'不验证':'验证'
                ],
                'ctime'     => $ctime
            ]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }
        return $blog;
    }

    /**
     * 更新 (显示包含code的消费信息) 状态
     * @param $data
     * @return bool
     */
    public function isCode($data)
    {
        $user_id        = $data['user_id'];
        $manage_id      = $data['manage_id'];

        $user_list      = Db::name("user")->find($user_id);
        $user_name      = $user_list['username'];
        $current_code   = $user_list['is_code'];
        if($current_code == 1){
            $new_check = 0;
        }else{
            $new_check = 1;
        }
        $blog = true;
        Db::startTrans();
        try{
            $ctime = getUtcTime();
            Db::name('user')->where(['id'=>$user_id])
                ->update(['is_code' => $new_check]);
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => "更新 (显示包含code的消费信息) 状态",
                'content'   => [
                    'username'      => $user_name,
                    'old_code'    => ($new_check == 1)?'显示':'不显示' ,
                    'new_code'    => ($new_check == 1)?'显示':'不显示'
                ],
                'ctime'     => $ctime
            ]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }
        return $blog;
    }

    public function editDataShow($data)
    {
        $user_id        = $data['user_id'];
        $manage_id      = $data['manage_id'];

        $user_list      = Db::name("user")->find($user_id);
        $user_name      = $user_list['username'];
        $data_show      = $user_list['data_show'];

        if($data_show == 1){
            $new_status = 0;
        }else{
            $new_status = 1;
        }
        $blog = true;
        Db::startTrans();
        try{
            $ctime = getUtcTime();
            Db::name('user')->where(['id'=>$user_id])
                ->update(['data_show' => $new_status ,'utime' => getUtcTime()]);
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => "change user data show",
                'content'   => [
                    'username'      => $user_name,
                    'old_status'    => $data_show ,
                    'new_status'    => $new_status
                ],
                'ctime'     => $ctime
            ]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }
        return $blog;
    }

    public function pwdChange($username,$password)
    {
        $user_list  = Db::name('user')->where(['username' => $username])->find();
        $ctime      = $user_list['ctime'];
        $user_id    = $user_list['id'];
        $new_pwd    = md5(md5($password) . $ctime);
        $re = Db::name('user')->where(['id'=>$user_id])->update([
            'password'  => $new_pwd,
            'utime'     => getUtcTime()
        ]);

        $userLogModel = new UserLog();
        $userLogModel->setLog($user_id , 'change pwd' ,['username' => $username , 'password' => $password]);
        return $re;
    }

    public function monthAmount($data)
    {
        $user_id    = $data['user_id'];
        $manage_id  = $data['manage_id'];
        $money      = trim($data['money']);
        $remark     = trim($data['remark']);

        $user_list          = Db::name('user')->find($user_id);
        $current_balance    = $user_list['balance'];
        $username           = $user_list['username'];
        $debt               = $user_list['debt'];

        $end_balance        = $current_balance - $money;
        $amount             = $money;
        if($end_balance < 0){
            $remark_amount  = abs($end_balance);
            $debt           += $remark_amount;
            $amount         = $current_balance;
            $end_balance    = 0;
            $remark         .= ". You currently owe $ {$remark_amount}";
        }
        $blog = true;
        Db::startTrans();
        try{
            $ctime = getUtcTime();
            //更新用户余额
            Db::name('user')->where(['id'=>$user_id])->update([
                'balance'   => $end_balance,
                'debt'      => $debt,
            ]);
            //记录钱包日志
            Db::name('user_cash_log')->save([
                'user_id'       => $user_id,
                'type'          => 1,//减少
                'action_type'   => 3,
                'amount'        => $amount,
                'balance'       => $end_balance,
                'desc'          => $remark,
                'ctime'         => $ctime,
            ]);
            //记录用户收费
            Db::name('user_fee')->save([
                'user_id'       => $user_id,
                'amount'        => $amount, //实际支付月费
                'should_amount' => $money,  //真实月费
                'remark'        => $remark,
                'ctime'         => $ctime
            ]);
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => 'user money fee',
                'content'   => ['username' => $username , 'amount fee' => $amount , 'remark' => $remark]
            ]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }
        return $blog;
    }

    public function changeMonthFee($data)
    {
        $user_id    = $data['user_id'];
        $manage_id  = $data['manage_id'];
        $money      = trim($data['money']);

        $user_list      = Db::name('user')->find($user_id);
        $old_month_fee  = $user_list['month_fee'];
        $username       = $user_list['username'];

        $re = Db::name('user')->where(['id'=>$user_id])->update(['month_fee'=>$money]);
        ManageLog::saveManageLog([
            'manage_id' => $manage_id,
            'desc'      => 'change Month Fee',
            'content'   => ['username' => $username , 'old Month Fee' => $old_month_fee , 'new Month Fee' => $money]
        ]);
        return $re;
    }

    public function changeUserName($data)
    {
        $user_id    = $data['user_id'];
        $manage_id  = $data['manage_id'];
        $new_name   = trim($data['new_name']);

        $user_list      = Db::name('user')->find($user_id);
        $user_num       = $user_list['user_num'];
        $old_username   = $user_list['username'];

        $re = Db::name('user')->where(['id'=>$user_id])->update(['username'=>$new_name]);
        Db::name('user_check')->where(['user_num'=>$user_num])->update(['username'=>$new_name]);

        ManageLog::saveManageLog([
            'manage_id' => $manage_id,
            'desc'      => 'change User Name',
            'content'   => ['old_username' => $old_username , 'new_username' => $new_name]
        ]);
        return $re;
    }

    public function sendMonthDept()
    {
        $list = Db::name('user')->where("debt >0")->select()->toArray();
        $data = [];
        foreach($list as $k=>$v){
            $username   = $v['username'];
            $debt       = $v['debt'];
            $data[]     = $username . '___' . $debt;
            EmailSend::sendEmail('debt_month' , ['email'=>$username ,
                'desc'=>"您的BetterEpay帐号已欠费($ {$debt})，请及时充值缴纳月租。"]);
        }
        return $data;
    }

    public function changeToken($data)
    {
        $business_token = trim($data['business_token']);
        $manage_id      = $data['manage_id'];
        $check_id       = $data['check_id'];
        $parent_id      = $data['parent_id'];

        $blog = true;
        Db::startTrans();
        try{
            $user_check_list= Db::name('user_check')->where(['id' => $check_id])->find();
            $username       = $user_check_list['username'];

            Db::name('user_check')->where(['id' => $check_id])
                ->update([
                    'business_token' => $business_token,
                    'check_status'   => 1,
                    'check_kyc'      => 2,   //2=已通过 ,因为这里用到了已通过的business_token
                    'check_result'   => 0,    //审核不通过的用户，使用了已通过的business_token,管理员可以再次选择
                    'parent_id'      => $parent_id
                ]);
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => 'Change Business Token',
                'content'   => ['username' => $username, 'business_token' => $business_token]
            ]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }
        return $blog;
    }

    public static function changeUserCardStatus($data,$manage_id)
    {
        $id_array   = $data['id_array'];
        $success_num =[];
        foreach ($id_array as $v){
            $user_id    = $v;
            $username = Db::name('user')->where(['id'=>$user_id])->value('username');
            $card_list  = Db::name('cards')
                ->where("is_del !=1 and is_action =0 and status=1 and user_id={$user_id}")
                ->select()->toArray();
            $success_card = 0;
            $success_card_num =[];
            if(!empty($card_list)){
                foreach ($card_list as $k_card=>$v_card){
                    $card_id        = $v_card['id'];
                    $card_type      = $v_card['card_type'];
                    $bank_type      = $v_card['bank_type'];
                    $card_num       = $v_card['card_num'];
                    $card_token     = $v_card['card_token'];
                    $type_api       = 'card_suspended';
                    $change_status  = "2";

                    if($bank_type == 3){
                        $data       = [
                            "user_id"       => $user_id,
                            "action_type"   => $type_api,
                            "cardGuid"      => $card_token,
                            "card_num"      => $card_num,
                            "request_data"  => [
                                "Activated" => false
                            ]
                        ];
                        $company_name = 'Connexpay';
                    }else{
                        $data       = [
                            "user_id"       => $user_id,
                            "action_type"   => $type_api,
                            "card_type"     => $card_type,
                            "bank_type"     => $bank_type,
                            "post_param"    => [
                                "card_num"       => $card_num
                            ]
                        ];
                        $company_name = 'Comdata';
                    }
                    $update_result = PublicApi::requestApi($company_name , $data);
                    $update_result_blog = $update_result['blog'];
                    if($update_result_blog){
                        $update_where = [
                            'status'=>  $change_status,
                            'utime' =>  getUtcTime()
                        ];
                        //更新卡列表状态
                        Db::name('cards')->where(['id'=> $card_id])->update($update_where);
                        $success_card_num[] = $card_num;
                        $success_card += 1;
                    }
                }
            }
            $re = Db::name('user')->where(['id'=>$user_id])->update(['status'=>2]);
            if($re){
                //记录管理员操作日志
                ManageLog::saveManageLog([
                    'manage_id' => $manage_id,
                    'desc'      => 'user_and_card_ice',
                    'time'      => getUtcTime(),
                    'content'   => json_encode([
                        'card_num' => $success_card_num,
                        'username' => $username
                    ])
                ]);
                EmailSend::sendEmail('ice_user' , [
                    'email'     => $username,
                    'desc'      => "
                    尊敬的客户，<br /><br />
                    希望您一切安好。作为CardEcho的运营方，我们通过此邮件与您联系，就您的账户和相关虚拟信用卡出现的重要问题向您说明。<br /><br />
                    首先，我们对您选择我们的平台作为虚拟信用卡需求的服务提供商表示衷心的感谢。我们深知流畅和可靠的支付体验的重要性，并致力于为客户提供最高水准的服务。<br /><br />
                    然而，我们最近发现您的账户存在异常高比例的拒付纠纷，这迫使我们对您的活动进行了彻底审查。遗憾的是，这导致了您的账户暂时被冻结，并冻结了所有相关的虚拟信用卡。<br /><br />
                    拒付纠纷对企业和金融机构都是一个严重的问题，因为它们可能导致财务损失和支付生态系统的混乱。为了维护我们平台的完整性和安全性，我们必须采取适当的措施来解决这类问题。<br /><br />
                    我们理解此次冻结可能给您带来不便，对此我们深表歉意。<br /><br />
                    我们理解您可能对此情况有疑虑或问题，因此鼓励您与我们专门的支持团队联系，联系方式为微信：sensir267 邮箱：support@cardecho.com。他们将非常乐意协助您，并在整个过程中提供任何必要的指导。<br /><br />
                    请注意，尽快解决此事对双方都是最为有利的。我们重视您作为客户的信任，并致力于尽快达成公平的解决方案。<br /><br />
                    再次，对可能给您带来的任何不便，我们深表歉意，并感谢您的合作和理解。我们期待解决此问题，并尽快恢复您的账户。<br /><br />
                    此致，<br /><br />
                    CardEcho运营小组<br />
                    ",
                    'title'     => "账户冻结通知 - 需要紧急处理 -- CardEcho",
                ]);
            }
            $success_num[] = [$username => $success_card];
        }
        return json_encode($success_num);
    }

    public static function changeUserStatus($data,$manage_id)
    {
        $id_array    = $data['id_array'];
        $success_num = 0;
        foreach ($id_array as $v){
            $user_id    = $v;
            $username = Db::name('user')->where(['id'=>$user_id])->value('username');
            $re = Db::name('user')->where(['id'=>$user_id])->update(['status'=>1]);
            if($re){
                //记录管理员操作日志
                ManageLog::saveManageLog([
                    'manage_id' => $manage_id,
                    'desc'      => 'user_and_card_active',
                    'time'      => getUtcTime(),
                    'content'   => json_encode([
                        'username' => $username
                    ])
                ]);
//                EmailSend::sendEmail('ice_user' , [
//                    'email'     => $username,
//                    'desc'      => "
//                    尊敬的客户，<br /><br />
//                    希望您一切安好。作为vvacard的运营方，我们通过此邮件与您联系，就您的账户和相关虚拟信用卡出现的重要问题向您说明。<br /><br />
//                    首先，我们对您选择我们的平台作为虚拟信用卡需求的服务提供商表示衷心的感谢。我们深知流畅和可靠的支付体验的重要性，并致力于为客户提供最高水准的服务。<br /><br />
//                    然而，我们最近发现您的账户存在异常高比例的拒付纠纷，这迫使我们对您的活动进行了彻底审查。遗憾的是，这导致了您的账户暂时被冻结，并冻结了所有相关的虚拟信用卡。<br /><br />
//                    拒付纠纷对企业和金融机构都是一个严重的问题，因为它们可能导致财务损失和支付生态系统的混乱。为了维护我们平台的完整性和安全性，我们必须采取适当的措施来解决这类问题。<br /><br />
//                    我们理解此次冻结可能给您带来不便，对此我们深表歉意。<br /><br />
//                    我们理解您可能对此情况有疑虑或问题，因此鼓励您与我们专门的支持团队联系，联系方式为微信：sensir267 邮箱：support@vvacard.com。他们将非常乐意协助您，并在整个过程中提供任何必要的指导。<br /><br />
//                    请注意，尽快解决此事对双方都是最为有利的。我们重视您作为客户的信任，并致力于尽快达成公平的解决方案。<br /><br />
//                    再次，对可能给您带来的任何不便，我们深表歉意，并感谢您的合作和理解。我们期待解决此问题，并尽快恢复您的账户。<br /><br />
//                    此致，<br /><br />
//                    vvacard运营小组<br />
//                    ",
//                    'title'     => "账户冻结通知 - 需要紧急处理 -- Vvacard",
//                ]);
                $success_num+=1;
            }
        }
        return $success_num;
    }

    public function updataUserData()
    {
        try {
            //取消内存限制
            ini_set('memory_limit', '-1');
            $fund_total_list = Db::name('fund_check')->field("DISTINCT(user_id)")
                ->where('check_status=1 and type=0 and user_id !=1')->select()->toArray();
            $userIdList =[];
            foreach ($fund_total_list as $k_fund=>$v_fund){
                if(!in_array($v_fund['user_id'] , $userIdList)){
                    $userIdList[] = $v_fund['user_id'];
                }
            }
            //用户充值credit
            $fund_credit_list = Db::name('fund_check')->field("sum(amount) amount , user_id")
                ->where("check_status = 1 and type = 0 and user_id !=1")->group('user_id')->select()->toArray();
            $new_fund_credit_list = [];
            foreach ($fund_credit_list as $k_credit => $v_credit){
                $new_fund_credit_list[$v_credit['user_id']] = $v_credit['amount'];
            }
            //var_dump(count($new_fund_credit_list));
            //充值总额-Debit
            $fund_list_debit = Db::name('fund_check')->field("sum(amount) amount , user_id")
                ->where("check_status = 1 and type = 1 and user_id !=1")->group('user_id')->select()->toArray();
            $new_fund_debit_list = [];
            foreach ($fund_list_debit as $k_debit => $v_debit){
                $new_fund_debit_list[$v_debit['user_id']] = $v_debit['amount'];
            }
            //var_dump(count($new_fund_debit_list));
            //卡可用余额
            $card_list = Db::name('cards')->field("sum(balance) balance,
                sum(balance_account) balance_account,
                count(*) card_count,
                sum(open_amount) open_amount,
                sum(refund_amount) refund_amount,
                sum(server_amount) server_amount , user_id")
                ->group('user_id')->select()->toArray();
            $new_card_list =[];
            foreach ($card_list as $k_card => $v_card){
                $new_card_list[$v_card['user_id']]['balance'] = $v_card['balance'];
                $new_card_list[$v_card['user_id']]['balance_account'] = $v_card['balance_account'];
                $new_card_list[$v_card['user_id']]['open_amount'] = $v_card['open_amount'];
                $new_card_list[$v_card['user_id']]['refund_amount'] = $v_card['refund_amount'];
                $new_card_list[$v_card['user_id']]['server_amount'] = $v_card['server_amount'];
                $new_card_list[$v_card['user_id']]['card_count'] = $v_card['card_count'];
            }
            //var_dump(count($new_card_list));
            $user_list = Db::name('user')->field('balance ,username , id')->select()->toArray();
            $new_user_list =[];
            foreach ($user_list as $k_user => $v_user){
                $new_user_list[$v_user['id']]['user_balance']   = $v_user['balance'];
                $new_user_list[$v_user['id']]['username']       = $v_user['username'];
            }
            //var_dump(count($new_user_list));
            $cancel_card_list = Db::name('cards')->field("count(*) card_count,user_id")
                ->where(['status' => 3])->group('user_id')->select()->toArray();
            $new_cancel_card_list =[];
            foreach ($cancel_card_list as $k_cancel => $v_cancel){
                $new_cancel_card_list[$v_cancel['user_id']] = $v_cancel['card_count'];
            }
            //var_dump(count($new_cancel_card_list));
            $tran_list = Db::name('cards_trans')->field("count(*) tran_count,user_id")
                ->group('user_id')->select()->toArray();
            $new_tran_list =[];
            foreach ($tran_list as $k_tran => $v_tran){
                $new_tran_list[$v_tran['user_id']] = $v_tran['tran_count'];
            }
            //var_dump(count($new_tran_list));
            $tran_Declined_list = Db::name('cards_trans')->field("count(*) tran_count,sum(amount_auth) amount_auth,user_id")
                ->where(['tran_status' => 'Declined'])->group('user_id')->select()->toArray();
            $new_tran_Declined_list =[];
            foreach ($tran_Declined_list as $k_tran_de => $v_tran_de){
                $new_tran_Declined_list[$v_tran_de['user_id']]['amount'] = $v_tran_de['amount_auth'];
                $new_tran_Declined_list[$v_tran_de['user_id']]['count'] = $v_tran_de['tran_count'];
            }
            //var_dump(count($new_tran_Declined_list));
            //拒付+0验证手续费(CD)
            $profit_cd_list = Db::name('server_cd')->field("sum(server_amount) amount,user_id")
                ->where(['is_action' => 1])->group('user_id')->select()->toArray();
            $new_profit_cd_list =[];
            foreach ($profit_cd_list as $k_profit_cd => $v_profit_cd){
                $new_profit_cd_list[$v_profit_cd['user_id']] = $v_profit_cd['amount'];
            }
            //拒付+0验证手续费(Lss)
            $profit_lss_list = Db::name('server_lss')->field("sum(server_amount) amount,user_id")
                ->where(['is_action' => 1])->group('user_id')->select()->toArray();
            $new_profit_lss_list =[];
            foreach ($profit_lss_list as $k_profit_lss => $v_profit_lss){
                $new_profit_lss_list[$v_profit_lss['user_id']] = $v_profit_lss['amount'];
            }
            //银3 货转服务费
            $profit_hz_list = Db::name('code_log')->field("sum(amount) amount,user_id")
                ->where(['is_action' => 1])->group('user_id')->select()->toArray();
            $new_profit_hz_list =[];
            foreach ($profit_hz_list as $k_profit_hz => $v_profit_hz){
                $new_profit_hz_list[$v_profit_hz['user_id']] = $v_profit_hz['amount'];
            }

            $new_list = [];
            $tran_credit_list = Db::name('cards_trans_credit')
                ->where(['credit_status' => 1])
                ->select()->toArray();
            foreach ($tran_credit_list as $k_credit=>$v_credit){
                $user_id = $v_credit['user_id'];
                if(isset($new_list[$user_id]['credit_ok'])){
                    $new_list[$user_id]['credit_ok'] += abs($v_credit['amount']);
                }else{
                    $new_list[$user_id]['credit_ok'] = abs($v_credit['amount']);
                }
            }

            //卡被银行强制消费
            $tran_fz_list = Db::name('cards_trans_fz')
                ->field("SUM(amount) amount,user_id")
                ->group('user_id')->select()->toArray();
            $tran_fz_array =[];
            foreach ($tran_fz_list as $k_tran_fz => $v_tran_fz){
                $tran_fz_array[$v_tran_fz['user_id']] = $v_tran_fz['amount'];
            }

            //获取所有消费信息
            $blog               = false;
            $current_time       = getUtcTime();
            $current_time_2     = getUtcTime(false);
            $new_data_list      = [];
            Db::startTrans();
            try {
                Db::name('user_data')->where('id >0')->delete();
                Db::name('user_data_diff')->where('id >0')->delete();
                foreach ($userIdList as $k => $v){
                    $user_id        = $v;
                    $new_data_list['user_id']     = $user_id;
                    $new_data_list['ctime']     = $current_time;

                    $new_data_list['auth'] = $tran_list[$user_id]['auth'] ?? 0.00;
                    $new_data_list['posted'] = $tran_list[$user_id]['posted'] ?? 0.00;
                    $new_data_list['credit'] = $tran_list[$user_id]['credit'] ?? 0.00;
                    $new_data_list['credit_ok'] = $new_list[$user_id]['credit_ok'] ?? 0.00;
                    $new_data_list['credit_556766'] = $tran_list[$user_id]['credit_556766'] ?? 0.00;
                    $new_data_list['reversal'] = $tran_list[$user_id]['reversal'] ?? 0.00;
                    $new_data_list['decline'] = $tran_list[$user_id]['decline'] ?? 0.00;
                    $un_credit = abs($new_data_list['credit']) - $new_data_list['credit_ok'];

                    $new_data_list['auth_3'] = $tran_list[$user_id]['auth_3'] ?? 0.00;
                    $new_data_list['posted_3'] = $tran_list[$user_id]['posted_3'] ?? 0.00;
                    $new_data_list['credit_3'] = $tran_list[$user_id]['credit_3'] ?? 0.00;
                    $new_data_list['reversal_3'] = $tran_list[$user_id]['reversal_3'] ?? 0.00;
                    $new_data_list['decline_3'] = $tran_list[$user_id]['decline_3'] ?? 0.00;

                    //卡被银行强制消费
                    $new_data_list['tran_qz_amount']   = $tran_fz_array[$user_id] ?? 0.00;

                    //银12消费总额
                    $tran_total_amount_12          = $new_data_list['auth'] +
                        $new_data_list['posted'] -
                        abs($new_data_list['credit']) -
                        abs($new_data_list['credit_556766']);
                    $tran_total_amount_12          = ($tran_total_amount_12 >0) ? getSprintf($tran_total_amount_12) : 0;
                    $new_data_list['tran_total_amount_1']   = $tran_total_amount_12;
                    //银3消费总额
                    $tran_total_amount_3        = $new_data_list['auth_3'] +
                        $new_data_list['posted_3'] -
                        abs($new_data_list['credit_3']) -
                        $new_data_list['reversal_3'];
                    //$tran_total_amount_3        = $new_data_list['auth_3'] + $new_data_list['posted_3'];
                    $tran_total_amount_3        = ($tran_total_amount_3 >0) ? getSprintf($tran_total_amount_3) : 0;
                    $new_data_list['tran_total_amount_3']   = $tran_total_amount_3;
                    $tran_total_amount  = $tran_total_amount_12 + $tran_total_amount_3;
                    $new_data_list['tran_total_amount']     = $tran_total_amount;
                    //用户余额
                    $new_data_list['user_balance']          = $new_user_list[$user_id]['user_balance'];
                    $new_data_list['username']          = $new_user_list[$user_id]['username'];
                    //充值总额-Debit|credit
                    $new_data_list['fund_total_debit']  = $new_fund_debit_list[$user_id] ?? 0.00;
                    $new_data_list['fund_total_credit'] = $new_fund_credit_list[$user_id]  -  $new_data_list['fund_total_debit'];

                    //卡金额统计
                    $new_data_list['card_balance']      = $new_card_list[$user_id]['balance'] ?? 0.00;
                    $new_data_list['card_total_balance']   = $new_card_list[$user_id]['balance_account'] ?? 0.00;
                    $new_data_list['card_tran_amount']  =
                        //$new_data_list['card_total_balance'] + $new_data_list['tran_qz_amount'] - $new_data_list['card_balance'] - $new_data_list['credit_ok'];
                        $new_data_list['card_total_balance'] - $new_data_list['card_balance'] - $new_data_list['credit_ok'];
                    $new_data_list['card_open_amount']  = $new_card_list[$user_id]['open_amount'] ?? 0.00;
                    $new_data_list['card_server_amount']= $new_card_list[$user_id]['server_amount'] ?? 0.00;
                    $new_data_list['card_refund_amount']= $new_card_list[$user_id]['refund_amount'] ?? 0.00;

                    $new_data_list['card_count']        = $new_card_list[$user_id]['card_count'] ?? 0;
                    $new_data_list['cancel_card_count'] = $new_cancel_card_list[$user_id] ?? 0;

                    //拒付+0验证
                    $new_data_list['profit_cd']         = $new_profit_cd_list[$user_id] ?? 0.00;
                    $new_data_list['profit_lss']        = $new_profit_lss_list[$user_id] ?? 0.00;


                    //银3货转服务费
                    $new_data_list['profit_hz']        = $new_profit_hz_list[$user_id] ?? 0.00;
                    //累计消费/开卡数量
                    $card_tran_rate = 0;
                    if($new_data_list['card_count'] > 0){
                        $card_tran_rate = getSprintf(round($new_data_list['tran_total_amount']/$new_data_list['card_count'],2));
                    }
                    $new_data_list['card_tran_rate'] = $card_tran_rate;
                    //拒付总金额
                    $tran_declined_amount  = $new_tran_Declined_list[$user_id]['amount'] ?? 0.00;
                    $new_data_list['tran_declined_amount'] = $tran_declined_amount;
                    //拒付总次数
                    $tran_declined_count    = $new_tran_Declined_list[$user_id]['count'] ?? 0;
                    $new_data_list['tran_declined_count'] = $tran_declined_count;

                    //消费总次数
                    $tran_count             = $new_tran_list[$user_id] ?? 0;
                    $new_data_list['tran_count'] = $tran_count;
                    //拒付比例
                    $tran_declined_rate = 0;
                    if($tran_count != 0){
                        $tran_declined_rate    = round($tran_declined_count/$tran_count ,2) * 100;
                        if($tran_declined_rate != 0){
                            $tran_declined_rate = getSprintf($tran_declined_rate);
                        }
                    }
                    $new_data_list['tran_declined_rate'] = $tran_declined_rate;
                    $total_amount_other =
                        $new_data_list['user_balance'] +
                        $new_data_list['card_balance'] +
                        $new_data_list['card_open_amount'] +
                        $new_data_list['card_server_amount'] +
                        $new_data_list['card_refund_amount'] +
                        $new_data_list['profit_cd'] +
                        $new_data_list['profit_lss'] +
                        $new_data_list['profit_hz'];

//                    $total_amount = $tran_total_amount + $total_amount_other + $un_credit;
                    $total_amount = 0.00;
                    $total_amount_1 = $new_data_list['card_tran_amount'] + $total_amount_other;

                    $new_data_list['total_amount'] = getSprintf($total_amount);
                    $new_data_list['total_amount_1'] = getSprintf($total_amount_1);

                    $re = Db::name('user_data')->save($new_data_list);

                    if(($new_data_list['total_amount_1'] - $new_data_list['fund_total_credit']) != 0){
                        $fund_total     = $new_data_list['fund_total_credit'];
                        $total_amount   = getSprintf($total_amount);
                        Db::name('user_data_diff')->save([
                            'user_id'       => $user_id,
                            'username'      => $new_data_list['username'],
                            'total_amount'  => $total_amount,
                            'total_amount_1'=> $total_amount_1,
                            'fund_total'    => $fund_total,
                            'diff_amount'   => $fund_total - $total_amount_1
                        ]);
                    }
                }
                $blog = true;
                Db::commit();
            } catch (\Exception $e) {
                $error_msg = $e->getMessage();
                var_dump($error_msg  . '---' .$e->getLine() );
                Db::rollback();
            }
            return [
                'blog'              => $blog,
                'time'              => $current_time_2,
            ];
        }catch (\Exception $e){
            dd($e->getMessage());
        }
    }

    public static function getTranData2()
    {
        $tran_list = Db::name('cards_trans')
            ->field('amount_auth,amount_post,tran_status,reversal_flag,ctime,card_num,bank_type,user_id')
            ->select()->toArray();

        $new_list = [];
        if($tran_list){
            foreach ($tran_list as $v){
                $reversal_flag  = $v['reversal_flag'];
                $ctime          = $v['ctime'];
                $bank_type      = $v['bank_type'];
                $tran_status    = $v['tran_status'];
                $user_id        = $v['user_id'];
                if($bank_type == 3){
                    switch ($tran_status){
                        case 'Authorized':
                            if(isset($new_list[$user_id]['auth_3'])){
                                $new_list[$user_id]['auth_3'] += $v['amount_auth'];
                            }else{
                                $new_list[$user_id]['auth_3'] = $v['amount_auth'];
                            }
                            break;
                        case 'Posted':
                            if(isset($new_list[$user_id]['posted_3'])){
                                $new_list[$user_id]['posted_3'] += $v['amount_post'];
                            }else{
                                $new_list[$user_id]['posted_3'] = $v['amount_post'];
                            }
                            break;
                        case 'Credit':
                            if(isset($new_list[$user_id]['credit_3'])){
                                $new_list[$user_id]['credit_3'] += $v['amount_post'];
                            }else{
                                $new_list[$user_id]['credit_3'] = $v['amount_post'];
                            }
                            break;
                        case 'Declined':
                            if(isset($new_list[$user_id]['declined_3'])){
                                $new_list[$user_id]['declined_3'] += $v['amount_auth'];
                            }else{
                                $new_list[$user_id]['declined_3'] = $v['amount_auth'];
                            }
                            break;
                        case 'Reversal':
                            if(isset($new_list[$user_id]['reversal_3'])){
                                $new_list[$user_id]['reversal_3'] += $v['amount_auth'];
                            }else{
                                $new_list[$user_id]['reversal_3'] = $v['amount_auth'];
                            }
                            break;
                    }
                }else{
                    switch ($tran_status){
                        case 'Authorized':
                            if($reversal_flag == 'N'){
                                if(isset($new_list[$user_id]['auth'])){
                                    $new_list[$user_id]['auth'] += $v['amount_auth'];
                                }else{
                                    $new_list[$user_id]['auth'] = $v['amount_auth'];
                                }
                            }else{
                                if(isset($new_list[$user_id]['reversal'])){
                                    $new_list[$user_id]['reversal'] += $v['amount_auth'];
                                }else{
                                    $new_list[$user_id]['reversal'] = $v['amount_auth'];
                                }
                            }
                            break;
                        case 'Posted':
                            if(isset($new_list[$user_id]['posted'])){
                                $new_list[$user_id]['posted'] += $v['amount_post'];
                            }else{
                                $new_list[$user_id]['posted'] = $v['amount_post'];
                            }
                            break;
                        case 'Credit':
                            $card_num6     = substr($v['card_num'] , 0 ,6);
                            if($card_num6 == '556766'){
                                if(isset($new_list[$user_id]['credit_556766'])){
                                    $new_list[$user_id]['credit_556766'] += abs($v['amount_post']);
                                }else{
                                    $new_list[$user_id]['credit_556766'] = abs($v['amount_post']);
                                }
                            }else{
                                if(isset($new_list[$user_id]['credit'])){
                                    $new_list[$user_id]['credit'] += abs($v['amount_post']);
                                }else{
                                    $new_list[$user_id]['credit'] = abs($v['amount_post']);
                                }
                            }
                            break;
                        case 'Declined':
                            if(isset($new_list[$user_id]['declined'])){
                                $new_list[$user_id]['declined'] += $v['amount_auth'];
                            }else{
                                $new_list[$user_id]['declined'] = $v['amount_auth'];
                            }
                            break;
                    }
                }
            }
        }
        $tran_credit_list = Db::name('cards_trans_credit')
            ->where(['credit_status' => 1])
            ->select()->toArray();
        foreach ($tran_credit_list as $k_credit=>$v_credit){
            $user_id = $v_credit['user_id'];
            if(isset($new_list[$user_id]['credit_ok'])){
                $new_list[$user_id]['credit_ok'] += $v_credit['amount'];
            }else{
                $new_list[$user_id]['credit_ok'] = $v_credit['amount'];
            }
        }
        return $new_list;
    }

    public function getCardSet($user_id)
    {
        $list = Db::name('user_set')->where(['user_id' => $user_id])
            ->order('type')->find();
        if(empty($list)){
            $type  = Db::name('user')->where(['id' => $user_id])->value('grade');
            //grade = 2时候，事管理员认证用户， 那么user_set 中type=1就按用户认证状态算
            if($type == 2){
                $type =1;
            }
            $list = Db::name('user_set')->where(['type' => $type , 'user_id'=>0])->find();
        }
        return $list;
    }

    public static function getTranData($user_id)
    {
        $tran_list = Db::name('cards_trans')
            ->field('amount_auth,amount_post,tran_status,reversal_flag,ctime,card_num')
            ->where("user_id={$user_id}")
            ->select()->toArray();
        $amount_auth        = 0.00;
        $amount_post        = 0.00;
        $amount_reversal    = 0.00;
        $amount_credit      = 0.00;
        $amount_credit_un   = 0.00;
        $amount_credit_556766   = 0.00;
        $amount_decline     = 0.00;
        if($tran_list){
            foreach ($tran_list as $v){
                $reversal_flag = $v['reversal_flag'];
                $ctime         = $v['ctime'];
                switch ($v['tran_status']){
                    case 'Authorized':
                        if($reversal_flag == 'N'){
                            $amount_auth        += $v['amount_auth'];
                        }else{
                            $amount_reversal   += $v['amount_auth'];
                        }
                        break;
                    case 'Posted':
                        $amount_post        += $v['amount_post'];
                        break;
                    case 'Credit':
                        $card_num6     = substr($v['card_num'] , 0 ,6);
                        if($card_num6 == '556766'){
                            $amount_credit_556766   += $v['amount_post'];
                        }else{
                            $credit_status = Db::name('cards_trans_credit')
                                ->where(['ctime'=>$ctime,'amount'=>abs($v['amount_post'])])->value('credit_status');
                            if($credit_status == 1){
                                $amount_credit      += $v['amount_post'];
                            }else{
                                $amount_credit_un   += $v['amount_post'];
                            }
                        }
                        break;
                    case 'Declined':
                        $amount_decline     += $v['amount_auth'];
                        break;
                }
            }
        }
        return [
            'amount_auth'       => $amount_auth,
            'amount_post'       => $amount_post,
            'amount_reversal'   => $amount_reversal,
            'amount_credit'     => $amount_credit,
            'amount_credit_un'  => $amount_credit_un,
            'amount_credit_556766' => $amount_credit_556766,
            'amount_decline'    => $amount_decline
        ];
    }
}
